import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';

@Injectable()
export class PrismaService
  extends PrismaClient
  implements OnModuleInit, OnModuleDestroy
{
  constructor() {
    super({
      log: [{ level: 'query', emit: 'event' }], // 这里设置日志级别
    });
  }

  async onModuleInit() {
    await this.$connect(); // 在模块初始化时连接到数据库
    // 监听查询事件并打印完整 SQL 和参数
    this.$on('query' as never, (event: any) => {
      console.log('--- Prisma Query Log ---');
      console.log('Query:    ', event.query); // SQL 语句
      console.log('Params:   ', event.params); // 具体参数值
      console.log('Duration: ', event.duration, 'ms');
      console.log('------------------------');
    });
  }

  async onModuleDestroy() {
    await this.$disconnect(); // 在应用程序关闭时断开与数据库的连
  }
}
